package com.zy.rpc.common.Serializer.impl;

import com.zy.rpc.common.Serializer.Serializer;

import java.io.*;

/**
 * @author zy
 * @date 2023/5/25 13:51
 */
public class JavaSerializer implements Serializer {
    @Override
    public <T> T deserialize(Class<T> clazz, byte[] bytes) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            // 使用 ObjectInputStream 从字节数组中反序列化对象
            return clazz.cast(ois.readObject());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public <T> byte[] serialize(T object) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            // 使用 ObjectOutputStream 将对象序列化为字节数组
            oos.writeObject(object);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }
}
